package com.atguigui.leetcode;

import java.util.Random;

/**
 * 478.在圆内随机生成点
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/6/5 18:35
 */
public class P478GenerateRandomPointInACircle {
    public static void main(String[] args) {
        Solution solution = new P478GenerateRandomPointInACircle().new Solution(1.0, 1, 1);
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {

        private Random random;
        private double radius;
        private double x_center;
        private double y_center;

        /**
         * 初始化
         *
         * @param radius   半径
         * @param x_center x轴坐标
         * @param y_center y轴坐标
         */
        public Solution(double radius, double x_center, double y_center) {
            random = new Random();
            this.radius = radius;
            this.x_center = x_center;
            this.y_center = y_center;
        }

        /**
         * 计算圆内任意一点
         *
         * @return
         */
        public double[] randPoint() {
            double u = random.nextDouble();
            //返回双精度值的正确正平方根
            double r = Math.sqrt(u);
            double theta = random.nextDouble() * 2 * Math.PI;

            return new double[]{x_center + r * Math.cos(theta) * radius, y_center + r * Math.sin(theta) * radius};

        }

        /**
         * 以2r为一个正方形，正方形内随机计算一个点，看是否在这个圆内
         *
         * @return
         */
        public double[] randPoint2() {
            //随机生成一个在2r正方行内的点
            while (true) {
                //最大的点落在正方行上
                double x = random.nextDouble() * (2 * radius) - radius;
                double y = random.nextDouble() * (2 * radius) - radius;
                // 计算面积是否圆内
                if (x * x + y * y <= radius * radius) {
                    return new double[]{x_center + x, y_center + y};
                }
            }
        }
    }
}
